#include "ftcombobox.h"
#include "ftcontrols.h"
#include "ftcomboboxdialog.h"

FTComboBox::FTComboBox() :
    QWidget()
{
    setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed);
    QSize arrow_size = FTControls::iconSize(FTControls::IconNormal);
    arrow_size.setWidth( arrow_size.width() / 2 );
    arrow = QPixmap(":/misc/combobox.png").scaled( arrow_size );
    selected = -1;
}

QSize FTComboBox::sizeHint() const
{
    QSize size;
    QFontMetrics fm(font());
    size = fm.size( Qt::TextSingleLine, "X" )+
           QSize( FTControls::defaultPadding()*2 + arrow.width(),
                  FTControls::defaultPadding() );
    if ( size.height() < FTControls::defaultHeight() )
        size.setHeight( FTControls::defaultHeight() );
    return size;
}

QSize FTComboBox::minimumSizeHint() const
{
    QSize size = sizeHint();
    size.setWidth( 5+arrow.width() );
    return size;
}

void FTComboBox::addItem( const QString& str )
{
    static int auto_key = -999999;
    addItem( auto_key, str );
    auto_key++;
}

void FTComboBox::addItem( int key, const QString& str )
{
    items.append( str );
    keys.insert( items.indexOf( str ), key );
}

int FTComboBox::selectedIndex() const
{
    return selected;
}

QString FTComboBox::selectedItem() const
{
    if ( (selected > -1) && (selected < items.count() ) )
        return items.at( selected );
    return "";
}

int FTComboBox::selectedItemId() const
{
    if ( (selected > -1) && (selected < items.count() ) )
        return keys.value( selected );
    return -9999999;
}

void FTComboBox::selectFirst()
{
    if ( items.count() > 0 )
        selected = 0;
    update();
}

void FTComboBox::selectLast()
{
    if ( items.count() > 0 )
        selected = items.count()-1;
    update();
}

void FTComboBox::clear()
{
    items.clear();
    keys.clear();
}

void FTComboBox::selectItem(QString str)
{
    if ( items.contains(str))
        selected = items.indexOf( str );
}

void FTComboBox::selectItem(int key)
{
    selected = keys.key( key, -1 );
}

void FTComboBox::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QString str;
    if ( (selected>-1) && (selected< items.count( )))
        str = items.at(selected);
    else
        str = tr("Please select...");
    painter.drawText(rect(),  Qt::AlignVCenter, str );
    painter.drawRect( rect().adjusted(1,1,-1,-1));
    painter.drawPixmap(width() - arrow.width(), 0, arrow);
}

void FTComboBox::mouseReleaseEvent(QMouseEvent *)
{
    FTComboBoxDialog dialog( items, selected );
    int tmp = dialog.userSelect();
    if ( (tmp>-1) && (tmp<items.count()))
    {
        selected = tmp;
        emit selectedItem( keys.value( selected ) );
        emit selectedItem( items.at(selected ) );
        emit selectedIndex( selected );
    }

}
